<template>
  <div class="menu">
    <header class="menu_header">
      <van-search v-model="searchValue" show-action placeholder="请输入菜品或菜品编号搜索" @search="onSearch" @cancel="onCancel" />
    </header>
    <van-empty description="该店暂无菜品" v-if="!dataSource.length > 0 && merchantId !== '-1'" />
      <section v-if="!merchantId || merchantId === '-1'" class="unselected">
        <van-empty description="请前往首页选择商家再点菜品" />
        <van-button class="unselected_button" round plain block type="primary" size="small" color="#754C29" @click="handleNavigateHome">前往首页</van-button>
      </section>

    <section class="menu_body">
      <Card v-for="item in dataSource" :key="item?.id">
        <section class="product">
          <van-image :src="`/api${item?.mainImage}`" v-if="item?.mainImage"  class="product_image"/>
          <p class="product_no">编号：{{ item?.productNo }}</p>
          <p class="product_name">菜品：{{ item?.name }}</p>
          <p class="product_tag">类别：<van-tag type="primary"> {{ item?.categoryName }}</van-tag></p>
          <p class="product_price">价格：{{ `¥ ${item?.price}元 / ${item?.unit}` }}</p>
          <p class="product_salesVolume">销量：{{ item?.salesVolume }}</p>
          <p class="product_status">状态：
            <van-tag type="success" v-if="item?.status === 1"> 上架</van-tag>
            <van-tag type="error" v-if="item?.status === 2"> 下架</van-tag>
          </p>
          <p class="product_description van-multi-ellipsis--l2" >
              描述：{{ item?.description }}
          </p>
          <van-button round block type="primary" size="small" color="#754C29" @click="handleAddCart(item)" :disabled="item?.status === 2">加入购物车</van-button>
          <van-button  round  style="margin-top: 4px;" block plain type="primary" size="small" color="#754C29" @click="handleNavigateDetail(item)">查看详情</van-button>
        </section>
      </Card>
    </section>
    <footer class="menu_footer">
      <van-pagination v-model="currentPage" :total-items="total" :items-per-page="10" @change="onPageChange" v-if="dataSource.length > 0" />
    </footer>
    <section style="height: 60px;">
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter,useRoute} from 'vue-router';
import { showToast,showFailToast,showSuccessToast,showConfirmDialog} from 'vant';
import {getProductList} from '@/apis/product';
import {addCart} from '@/apis/cart';
import Card from '@/components/Card/index.vue';
import { useCartStore } from '@/stores/cart';

const route = useRoute();
const router = useRouter();
const cartStore = useCartStore();
const merchantId = localStorage.getItem('merchantId') || -1;
localStorage.setItem('merchantId', route.params?.id !== '-1' ?  route.params?.id : merchantId);

const searchValue = ref('');
const currentPage = ref(1);
const total = ref(0);
const dataSource = ref([]);
const token = localStorage.getItem('token');

const onSearch = async (value) => {
  if(!merchantId){
    showFailToast("请选择商家后再搜索菜品");
    return;
  }
  try {
    const { data = {} } = await getProductList({
      merchantId,
      searchValue:value,
      pageNum: currentPage.value,
      pageSize: 10,
    });
    if (!data?.list?.length) {
      showToast({
        message: '暂无数据，联系管理员添加吧',
        duration: 2000,
      });
      return;
    }
    showToast({
      message: '搜索结果如下',
      duration: 2000,
    });
    dataSource.value = data?.list || [];
    total.value = data?.total || 0;

  } catch (error) {
    console.log(error, 'error');

  }
};
const onCancel = () => {
  searchValue.value = '';
  init();
  showToast('取消');
};
const init = async () => {
  if(!merchantId){
    return;
  }
  try {
    const { data = {} } = await getProductList({
      merchantId,
      pageNum: currentPage.value,
      pageSize: 10,
    });
    dataSource.value = data?.list || [];
    total.value = data?.total || 0;

  } catch (error) {
    console.log(error, 'error');

  }
};


const onPageChange = async (current) => {
  try {
    const { data = {} } = await getProductList({
      pageNum: current,
      pageSize: 10,
      merchantId,
    });
    dataSource.value = data?.list || [];



    total.value = data?.total || 0;

  } catch (error) {
    console.log(error, 'error');

  }
};

const handleNavigateDetail = (item) => {
  router.push(`/product/${item?.id}`)
}

const handleNavigateHome = () => {
  router.push('/home');
}

const handleAddCart = async (item) => {
  if(!token){
      showConfirmDialog({
        title: '提示',
        message: '请先登录',
      }).then(() => {
        router.push('/login');
      }).catch(() => {});
      return;
    }
  try {
      const {code,msg} = await addCart({
        productId:item?.id,
      });
      if(code === 200){
        showSuccessToast('成功加入购物车');
        cartStore?.init();
        return;
      }
      showFailToast(msg);

  } catch (error) {
    console.log(error,'error');

  }
};

onMounted(() => {
  init()
})
</script>

<style lang="less" scoped>
.menu{
  &_footer{
    margin-top: 8px;
  }
}
.product{
  margin-top: 8px;
  &_image{
    width: 100%;
    height: 132px;
  }
  &_no{
    margin-top: 4px;
    font-size: 14px;
    color: #666;
  }
  &_name{
    margin-top: 4px;
    font-size: 14px;
    color: #333;
  }
  &_tag{
    margin-top: 4px;
    font-size: 14px;
    color: #666;
  }
  &_price{
    margin-top: 4px;
    font-size: 14px;
    color: #f50;
  }
  &_salesVolume{
    margin-top: 4px;
    font-size: 14px;
    color: #666;
  }
  &_status{
    margin-top: 4px;
    font-size: 14px;
    color: #666;
  }
  &_description{
    margin-top: 4px;
    font-size: 12px;
    color: #999;
  }
}
.unselected{
  margin-top: 8px;
  text-align: center;
  width: 96%;
  &_button{
    width: 160px;
    margin: 0 auto;
  }
}
</style>
